package com.ys.controller.api.hr;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.hr.ThrTransparencyProgram;
import com.ys.entity.hr.ThrTransparencyProgramItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.finance.PaymentEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.service.flow.YspTaskService;
import com.ys.service.hr.ThrTransparencyProgramService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 *透明计划申报
 */
@Controller
@RequestMapping("/api/inter/thrTransparencyProgram")
public class ApiInterThrTransparencyProgramController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterThrTransparencyProgramController.class);


    @Autowired
    private CommonApiService<ThrTransparencyProgram> commonApiService;
    @Autowired
    private CommonApiService<ThrTransparencyProgramItem> commonApiServiceItem;
    @Autowired
    private ThrTransparencyProgramService thrTransparencyProgramService;

    @Autowired
    private YspTaskService yspTaskService;

    //权限字符
    private final String PERMISSIONS_EXPORT = "thrTransparencyProgram:export";
    private final String PERMISSIONS_ADD = "thrTransparencyProgram:add";
    private final String PERMISSIONS_CANCEL = "thrTransparencyProgram:cancel";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public ThrTransparencyProgram setSeachSql(ThrTransparencyProgram cond,String conditions){
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");

        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
        .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
        .addLeftJoin("THR_TransparencyProgramItem tpi on  tpi.transparencyProgramBid = A.bid")//透明计划申报明细
                .addField("tpi.billingMonth AS billingMonth,tpi.billingAmount AS billingAmount,tpi.platformBid AS platformBid,tpi.annexFile AS annexFile,tpi.id AS transparencyProgramId,tpi.statePay AS statePay")
        .addLeftJoin("TB_PlatformServicePayAccount tpsa ON  tpsa.id = tpi.ptId")//平台付款管理
                .addField("tpsa.vyhzhmc AS vyhzhmc,tpsa.vkhh AS vkhh,tpsa.achRouting AS achRouting,tpsa.vyhzh AS vyhzh,tpsa.swiftCode AS swiftCode,tpsa.serviceName AS serviceName,tpsa.platformCode AS platformCode")
        .addLeftJoin("TP_AmazonShopExchangeRate ter ON  ter.id = tpsa.AmazonShopExchangeRateld")//币种管理
                .addField("ter.code AS exchangeRateCode")
        .addLeftJoin("THR_OperateCompanyApply toca ON  toca.vgsbm = tpi.vgsbm")//运营公司
                .addField("toca.vgsbm AS vgsbm,toca.vgsjc AS vgsjc,toca.Cuser AS cUser")

        //排序
        .setOrderby("A.createTime DESC");
        cond = commonApiService.dataAuth(MenuId.THR_TransparencyProgram, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("thrTransparencyProgram:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute ThrTransparencyProgram cond,String conditions){
        cond = setSeachSql(cond,conditions);
        LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
        return tableVoJA;
    }


    /**
     * 查询(弹出框)
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute ThrTransparencyProgramItem cond){
    	
    	cond.setStatePay(PaymentEnum.StatePay.INIT.value);
    	
		cond.addLeftJoin("THR_OperateCompanyApply B on B.Vgsbm = A.Vgsbm")
			.addField("B.Vgsbm vgsbm")
			.addField("B.Vgsjc vgsjc");
		
		cond.addLeftJoin("TB_PlatformServicePayAccount C ON C.Id = A.PtId")
			.addField("C.Vyhzhmc vyhzhmc")
			.addField("C.Vyhzh vyhzh")
			.addField("C.AchRouting vaba")
			.addField("C.Vkhh vkhh")
			.addField("C.SwiftCode swiftCode");

    	
    	cond.addLeftJoin("THR_TransparencyProgram D ON D.Bid = A.TransparencyProgramBid")
    		.addField("D.Bid bid")
    		.addField("D.EffectStock effectStock")
    		.where("D.EffectStock = " + FlowEnum.EffectStock.EFFECTED.value);
    	
    	cond.addLeftJoin("TP_AmazonShopExchangeRate E ON E.Id = C.AmazonShopExchangeRateld")
    		.addField("E.Code currencyCode");
    	
    	cond.addField("A.ptId vbzCode");
		
    	return commonApiServiceItem.searchLay(cond);
    }


    /**
     * 导出
     */
    @RequiresPermissions(PERMISSIONS_EXPORT)
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute ThrTransparencyProgram cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond,conditions);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.THR_TransparencyProgram)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<ThrTransparencyProgram> util = new ExportExcelUtils<>(new ThrTransparencyProgram());
            String toFilePath = util.exportExcel(listData, listField, "透明计划申报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData){
        try {
            //新增
            return thrTransparencyProgramService.add(params,subData);
        } catch (Exception e) {
            logger.error("透明计划申报新增出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 编辑
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData){
        try {
            //新增
            return thrTransparencyProgramService.edit(params,subData);
        } catch (Exception e) {
            logger.error("透明计划申报修改出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }



    /**
     * 流转通过
     */
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
    		ThrTransparencyProgram entity = new ThrTransparencyProgram().setId(id).queryFirst();
    		String bid = entity.getBid();
            return thrTransparencyProgramService.flowPass(bid, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("印章申请表流转出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        ThrTransparencyProgram entity = new ThrTransparencyProgram().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("透明计划申报转驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 流转退回
     */
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        try {
            ThrTransparencyProgram entity = new ThrTransparencyProgram().setId(id).queryFirst();
            return yspTaskService.flowInit(entity.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return thrTransparencyProgramService.del(id);
        } catch (Exception e) {
            logger.error("删除透明计划申报出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 作废
     */
    @RequiresPermissions(PERMISSIONS_CANCEL)
    @PostMapping("/cancel")
    @ResponseBody
    public R cancel(String bid,Long id){
        try {
            return thrTransparencyProgramService.cancel(bid,id);
        } catch (Exception e) {
            logger.error("作废透明计划申报出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


}